package com.mall.b2c.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import com.mall.common.bean.Pager;
import com.mall.common.util.AppContext;
import com.mall.common.util.CommonSettingUtils;
import com.mall.common.util.DateHelper;
import com.mall.common.util.PropertiesHelper;
import com.mall.common.util.SpringUtils;

public class JsonDataGridHelper {
	
	@SuppressWarnings("unchecked")
	public static Pager createJSONData(Pager pager){
		if(pager == null){
			return null;
		}
		List<Object> dataList = pager.getList();
		pager.setList(createJSONData(dataList));
		return pager;
	}
	
	/**
	 * 将page类转换成ligerUI Grid框架所需的JSON格式数据。
	 * @param data
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List<Object> createJSONData(List dataList){
		Map<String, String> fieldMap = new HashMap<String, String>();
		List<Object> list = new ArrayList<Object>();
		HttpServletRequest request = AppContext.getRequest();
		String filedStr = request.getParameter("field");
		if(StringUtils.isEmpty(filedStr)){
			return null;
		}
		String[] field = filedStr.split(",");
		String[] dict = StringUtils.splitPreserveAllTokens(request.getParameter("dict"), ",");
		String[] i18n = StringUtils.splitPreserveAllTokens(request.getParameter("i18n"), ",");
		String[] sdict = StringUtils.splitPreserveAllTokens(request.getParameter("sdict"), ",");
		for(Object data: dataList){
			Map<String,String> keyValue = new HashMap<String,String>();
			for(int i = 0; i < field.length;i++){
				String value = getValueByOgnl(data, field[i],"");
				if (i18n != null && i18n[i].trim().length()>0 && !StringUtils.isBlank(value)){
					String fieldName = null;
					if(fieldMap.containsKey(field[i])){
						fieldName = fieldMap.get(field[i]);
					}else{
						fieldName = StringUtils.capitalize(i18n[i]);
					}
					String propertiesValue = SpringUtils.
						getMessage(fieldName + "." + value, null);
					keyValue.put(field[i], propertiesValue);
				}else if (dict != null && dict[i].trim().length()>0 && !StringUtils.isBlank(value)){
					String propertiesValue = PropertiesHelper.getPropertiesValue("i18n_zh_CN", 
            			dict[i] + "." + getValueByOgnl(data, field[i],""));
					
					if(StringUtils.isNotEmpty(propertiesValue) && propertiesValue.contains("${base}")){
						propertiesValue = StringUtils.replace(propertiesValue, "${base}", request.getContextPath());
					}
                    keyValue.put(field[i], propertiesValue);
                }else if (sdict != null && sdict[i].trim().length()>0 && !StringUtils.isBlank(value)){ 
                	JSONObject jObj = CommonSettingUtils.getDictionaryDataForJSON(value);
                	if(jObj != null){
                		Object fieldValue = jObj.get("name");
                		if(fieldValue != null){
                            keyValue.put(field[i], fieldValue.toString());
                		}
                	}
                }else{
					keyValue.put(field[i],  getValueByOgnl(data, field[i],""));
				}
			}
			list.add(keyValue);
		}
		return list;
	}
	
	/**
	 * 根据数据源中所列的字段获取值,为NULL时 需要设置默认值(待完善)
	 * @param data
	 * @return
	 * @throws OgnlException 
	 */
	private static String getValueByOgnl(Object target,String field,String defaultValue) {
		String resultValue = "";
		
		Object value = null;
		try {
			value = BeanUtils.getProperty(target, field);
		} catch (Exception e) {
			return defaultValue;
		}
		if(null != value){
			if(value instanceof Date || value instanceof java.sql.Date){
				resultValue = DateHelper.date2String((Date)value, "yyyy-MM-dd HH:mm:ss");
			}else{
				resultValue = String.valueOf(value);
			}
		}
		return resultValue;
	}
}
